import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/moment_shot.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/dialog_lens.dart';
import 'package:vista/shared/services/post_studio.dart';
import 'package:vista/shared/services/relation_bond.dart';

/// 他人主页视图模型
/// 管理他人主页页面的数据和状态
class OtherProfileViewModel extends BaseViewModel {
  final AuthFocus _authFocus;
  final PostStudio _postStudio;
  final RelationBond _relationBond;
  final DialogLens _dialogLens;
  final String targetUserId;

  OtherProfileViewModel(
    this._authFocus,
    this._postStudio,
    this._relationBond,
    this._dialogLens,
    this.targetUserId,
  );

  UserFrame? _targetUser;
  UserFrame? get targetUser => _targetUser;

  UserFrame? _currentUser;
  UserFrame? get currentUser => _currentUser;

  List<MomentShot> _targetPosts = [];
  List<MomentShot> get targetPosts => _targetPosts;

  List<MomentShot> _likedPosts = [];
  List<MomentShot> get likedPosts => _likedPosts;

  int _postCount = 0;
  int get postCount => _postCount;

  int _likeCount = 0;
  int get likeCount => _likeCount;

  int _friendCount = 0;
  int get friendCount => _friendCount;

  bool _isFollowing = false;
  bool get isFollowing => _isFollowing;

  Map<String, UserFrame> _userMap = {};
  UserFrame? getUserById(String userId) => _userMap[userId];

  Map<String, int> _likeCountMap = {};
  int getLikeCount(String postId) => _likeCountMap[postId] ?? 0;

  /// 初始化数据
  Future<void> initialize() async {
    setBusy(true);
    try {
      await _loadCurrentUser();
      await _loadTargetUser();
      if (_targetUser != null) {
        await _loadUsers();
        await _loadTargetPosts();
        await _loadLikedPosts();
        await _loadStatistics();
        await _loadLikeCounts();
        await _loadFollowStatus();
      }
    } finally {
      setBusy(false);
    }
  }

  /// 加载当前用户
  Future<void> _loadCurrentUser() async {
    _currentUser = await _authFocus.getCurrentUser();
    notifyListeners();
  }

  /// 加载目标用户
  Future<void> _loadTargetUser() async {
    final users = await _authFocus.getUsers();
    _targetUser = users.firstWhere(
      (user) => user.id == targetUserId,
      orElse: () => users.first,
    );
    notifyListeners();
  }

  /// 加载目标用户的动态
  Future<void> _loadTargetPosts() async {
    if (_targetUser == null) return;
    _targetPosts = await _postStudio.getPostsByUser(_targetUser!.id);
    notifyListeners();
  }

  /// 加载用户信息
  Future<void> _loadUsers() async {
    final users = await _authFocus.getUsers();
    _userMap = {for (var user in users) user.id: user};
    notifyListeners();
  }

  /// 加载点赞的动态
  Future<void> _loadLikedPosts() async {
    if (_targetUser == null) return;
    _likedPosts = await _postStudio.getLikedPostsByUser(_targetUser!.id);
    notifyListeners();
  }

  /// 加载点赞数量
  Future<void> _loadLikeCounts() async {
    final allPosts = [..._targetPosts, ..._likedPosts];
    for (final post in allPosts) {
      _likeCountMap[post.id] = await _postStudio.getLikeCount(post.id);
    }
    notifyListeners();
  }

  /// 加载统计数据
  Future<void> _loadStatistics() async {
    if (_targetUser == null) return;

    _postCount = _targetPosts.length;

    // 计算总点赞数（目标用户所有动态的点赞数之和）
    int totalLikes = 0;
    for (final post in _targetPosts) {
      totalLikes += await _postStudio.getLikeCount(post.id);
    }
    _likeCount = totalLikes;

    // 获取朋友数量
    final friendIds = await _relationBond.getFriendsList(_targetUser!.id);
    _friendCount = friendIds.length;

    notifyListeners();
  }

  /// 加载关注状态
  Future<void> _loadFollowStatus() async {
    if (_currentUser == null) {
      _isFollowing = false;
      notifyListeners();
      return;
    }

    _isFollowing = await _relationBond.isFollowing(
      followerId: _currentUser!.id,
      followingId: targetUserId,
    );
    notifyListeners();
  }

  /// 切换关注状态
  Future<void> toggleFollow() async {
    if (_currentUser == null) return;

    setBusy(true);
    try {
      if (_isFollowing) {
        await _relationBond.unfollowUser(
          followerId: _currentUser!.id,
          followingId: targetUserId,
        );
      } else {
        await _relationBond.followUser(
          followerId: _currentUser!.id,
          followingId: targetUserId,
        );
      }
      await _loadFollowStatus();
    } finally {
      setBusy(false);
    }
  }

  /// 检查是否有与用户的对话
  Future<bool> hasChatWithUser() async {
    if (_currentUser == null) return false;

    final messages = await _dialogLens.getChatMessages(
      userId1: _currentUser!.id,
      userId2: targetUserId,
    );

    return messages.isNotEmpty;
  }

  /// 创建对话（发送一条初始消息）
  Future<void> createChatWithUser() async {
    if (_currentUser == null) return;

    await _dialogLens.sendTextMessage(
      senderId: _currentUser!.id,
      receiverId: targetUserId,
      content: 'Hello!',
    );
  }

  /// 刷新数据
  Future<void> refresh() async {
    await initialize();
  }
}
